package library.controller;


import java.sql.SQLException;
import java.util.List;

import library.DaoUtil;
import library.ErrorCode;
import library.ErrorMessage;

import com.j256.ormlite.dao.Dao;

public abstract class AbstractController<T> {
	private Dao<T, String> dao;
    protected ErrorMessage lastError;
	
	public AbstractController(Class<T> cls) throws SQLException{
		dao = DaoUtil.getDao(cls);
	}
	
	protected boolean insert(T t) {
		try {
			return(dao.create(t) == 1);
		} catch (SQLException e) {
            lastError = new ErrorMessage(ErrorCode.UNEXPECTED_ERROR, e);
            return false;
		}
	}
	
	protected boolean update(T t){
		try {
			return dao.update(t) == 1;
		} catch (SQLException e) {
            lastError = new ErrorMessage(ErrorCode.UNEXPECTED_ERROR, e);
            return false;
		}
	}
	
	protected List<T> select(String columnName, Object value) throws SQLException{
		return dao.queryForEq(columnName, value);
	}
	
	protected T selectOnce(String columnName, Object value) throws SQLException{
		List <T> result = dao.queryForEq(columnName, value);
		if(result == null || result.size() <= 0)
			return null;
		else
			return result.get(0);
	}
	
	protected boolean delete(T t) {
		try {
			return dao.delete(t) > 0;
		} catch (SQLException e) {
			lastError = new ErrorMessage(ErrorCode.UNEXPECTED_ERROR, e);
            return false;
		}
	}

	protected T selectById(int id) throws SQLException{
		T result = dao.queryForId(String.valueOf(id));
		return result;
	}

	protected T selectById(T t) throws SQLException{
		T result = dao.queryForSameId(t);
		return result;
	}
	
	public Dao<T, String> getDao(){
		return dao;
	}
	
    public ErrorMessage getError(){
        ErrorMessage err = lastError;
        lastError = null;
        return err;
    }
}
